import {Injectable} from "@angular/core";
import {Http, Response,Headers} from "@angular/http";
import { Mistake } from "./mistake";
import { PointList } from "./pointList";
import { Observable} from "rxjs/Rx";
import {Question} from "./question";

@Injectable()

export class MistakeService{
    public token:string;
    public url = 'http://127.0.0.1:8080/';
    // public url = "http://127.0.0.1:8080";
    //private localUrl = "http://127.0.0.1:8080/";//'http://127.0.0.1:8080/';
    //private searchUrl = "http://127.0.0.1:8080";
    private getAllMistakeurl = this.url+'/mistake/getAllMistakes';
    private IDUrl =  this.url+'/mistake/getMistakeById';
    private timeUrl = this.url+'/mistake/getAllMistakesByTime';
    private pointsUrl = this.url+'/mistake/getMistakesByPoints';
    private getAllPointListUrl = this.url+'/mistake/getAllPoints';
    private submitUrl = this.url+'/mistake/saveMistakes';
    private testSubmitUrl = this.url+'/mistake/save';
    private submitImgUrl = this.url+'/mistake/convertToImg';
    private submitImgUrl2 = this.url+'/mistake/savePicture';
    private uploadBaseUrl = this.url+'/api/question/searchByBase64';
    private substituteByTextUrl = this.url + '/api/question/searchByText';
    private substituteUrl = this.url + '/json/getPicMessage';
    private getQuestionUrl = this.url + '/api/question/findById';
    private getMistakeUrlByCourse = this.url + '/mistake/getMistakeByCourse';


    constructor(private http:Http){

    }

    getMistake():Promise<Mistake[]>{
        return this.http.get(this.getAllMistakeurl).toPromise()
        .then(this.extractData)
        .catch(this.handleError);
    }
  getMistakeByCourse(subject:string,username:string):Promise<Mistake[]>{
    let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
    //var body = {'questionTitle': questionTitle}
    return this.http.get(this.getMistakeUrlByCourse+"?course="+ subject+"&username="+username,{headers: token_headers}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

    getMistakeById(getIDUrl:string):Promise<Mistake>{
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
      return this.http.get(getIDUrl,{headers: token_headers}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
    }

    getMistakesByTime():Promise<Mistake[]>{
      return this.http.get(this.timeUrl).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }
    getPointList():Promise<PointList[]>{
      return this.http.get(this.getAllPointListUrl).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
    }

    getSubstituteList(): Observable < string[] > {
      return this.http.get(this.substituteUrl).map((response: Response) => {
          return <string[] > response.json()
      }).catch(this.handleError);
  }

    getMistakesByPoints(getPointsUrl:string):Promise<Mistake[]>{
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
      return this.http.get(getPointsUrl,{headers: token_headers}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
    }

    submitMistakes(submitMistakes : Mistake):Promise<void>{
      var points = encodeURIComponent(submitMistakes.points);
      var reason = encodeURIComponent(submitMistakes.reason);
      var source = encodeURIComponent(submitMistakes.source);
      var course = encodeURIComponent(submitMistakes.course);
      var content = encodeURIComponent(submitMistakes.content);
      var body = "misId="+submitMistakes.misId +"&sourceId="+submitMistakes.sourceId
        +"&points="+ points+"&masterDegree="+submitMistakes.masterDegree
        +"&familarIds="+submitMistakes.familarIds+"&source="+source
        +"&buildTime="+submitMistakes.bulidTime+"&editTime="+submitMistakes.editTime
        +"&reason=" +reason+"&course="+course+"&content="+content
        +"&answPicUrl="+submitMistakes.answPicUrl+"&quesPicUrl="+submitMistakes.quesPicUrl
      +"&username="+submitMistakes.username;
      console.log("body:"+body);
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded;charset=gbk'});
      console.log(token_headers);
      return this.http.post(this.submitUrl,body,{headers: token_headers})
        .toPromise()
        .then((res:Response)=>{console.log(res)});
    }

    submitImg(picStr:string):Promise<void>{
      var body = "picUrl="+picStr;
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
      console.log(token_headers);
      return this.http.post(this.submitImgUrl,body,{headers: token_headers}).toPromise()
          .then((res:Response)=>{console.log(res)});
    }


    uploadBase64(base64:string):Promise<JSON>{
      //var body = "base64DataJson="+base64;
     // var body = JSON.stringify({'base64DataJson': base64});
      var body ={'base64DataJson': base64};
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
     let token_header2 = new Headers({'Content-Type':'application/json','authorization':this.token})
      console.log(token_headers);
      return this.http.post(this.uploadBaseUrl,body,{headers: token_header2}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);  ;

    }
    getQuestionById(questionUid:number):Promise<Question>{
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
      //var body = {'questionTitle': questionTitle}
      return this.http.get(this.getQuestionUrl+"?id="+ questionUid,{headers: token_headers}).toPromise()
        .then(this.extractData)
        .catch(this.handleError);
  }

    substituteByText(questionTitle:string):Promise<JSON>{
      let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
      //var body = {'questionTitle': questionTitle}
      return this.http.get(this.substituteByTextUrl+"?questionTitle="+ questionTitle,{headers: token_headers}).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
    }



    private extractData(res: Response) {
        let body = res.json();
        //将拿到的hero数据进行打印....
        console.log("即将开始对Mistake数据的打印-----");
        console.log(body);
        console.log("结束对Mistake数据的打印-----");

        return body;
      }
      private handleError (error: Response | any) {
        console.log("有错误???");
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.log(errMsg);
        return Promise.reject(errMsg);
      }

}
